package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopRates;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.mapper.ShopRatesMapper;
import com.hmdp.service.ShopRatesService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ShopRatesServiceImpl extends ServiceImpl<ShopRatesMapper, ShopRates> implements ShopRatesService {
    @Resource
    private ShopRatesMapper shopRatesMapper;

    @Resource
    private ShopMapper shopMapper;

    @Override
    public Result saveRates(ShopRates shopRates) {
        // 查询商店评分
        QueryWrapper<ShopRates> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("shop_id", shopRates.getShopId());
        ShopRates existingRates = shopRatesMapper.selectOne(infoQueryWrapper);

        QueryWrapper<Shop> shopQueryWrapper = new QueryWrapper<>();
        shopQueryWrapper.eq("id", shopRates.getShopId());
        Shop shop = shopMapper.selectOne(shopQueryWrapper);
        if(existingRates == null||existingRates.getCounts()==null){
            System.out.println(shopRates.getShopId());
            return Result.fail("商店评分记录不存在");
        }

        float mod= (float) ((existingRates.getCounts()) * 5.0);
        // 更新评分
        float overall=existingRates.getOverall() + shopRates.getOverall()/mod;
        existingRates.setOverall(overall);
        existingRates.setEnvironment(existingRates.getEnvironment() + shopRates.getEnvironment()/mod);
        existingRates.setTaste(existingRates.getTaste() + shopRates.getTaste()/mod);
        existingRates.setCounts(existingRates.getCounts() + 1);
        existingRates.setAllScore((existingRates.getCounts() + 1)*5);

        shop.setScore(overall);
        shopMapper.updateById(shop);

        // 更新数据库
        shopRatesMapper.updateById(existingRates);

        return Result.ok(existingRates.getShopId());
    }
}
